<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>迭代器iterator</title>
</head>
<body>
    
</body>
<script>
    // 自定义一个迭代器
    function makeIterator(arr){
        let index = 0
        return {
            next: function(){
                if(index < arr.length){
                    return {value: arr[index++], done: false}
                }
                return{value:undefined, done:true}
            }
        }
    }

    let arr = [1,2,3,4,5]
    let str = 'hello'
    let obj = {name:'hh',id:1}
    let it = makeIterator(arr)

    let res = it.next()
    while(!res.done){
        console.log(res)
        res=it.next()
    }

    // console.log(it.next())
    // console.log(it.next())
    // console.log(it.next())
    // console.log(it.next())
    // console.log(it.next())
    // console.log(it.next())
    // console.log(it.next())

    // for...of 有迭代器对象的可以使用for...of，像Array、Map、Set、String、TypeArray、arguments、NodeList都有迭代器,在原型上
    // for...in 遍历的是key值
    console.log(arr,  arr[Symbol.iterator])
    console.log(str, str.__proto__,  str[Symbol.iterator])
    for(let i of arr){
        console.log(i)
    }
    for(let i of str){
        console.log(i)
    }
    for(let i in obj){
        console.log(i)
    }
    for(let i in arr){
        console.log(i)
    }
    for(let i in str){
        console.log(i)
    }

    // 给一个对象添加一个迭代器方法
    let object = {
        id: 1,
        name: 'hh',
        age: 18,
        [Symbol.iterator](){
            let index = 0
            let map = new Map([['id',1],['name','hh'],['age',18]])
            // mapArr.set('id', 1)
            // mapArr.set('name', 'hh')
            // mapArr.set('age', 18)
            console.log(map.keys())
            console.log(map.values())
            console.log(map.entries())
            console.log(map.size)
            
            let mapArr = [...map.entries()]
            console.log(mapArr)

            return {
                next(){
                    if(index < mapArr.length){
                        return {value: mapArr[index++], done: false}
                    }
                    return {value: undefined, done: true}
                }
            }
        }
    }

    let iter = object[Symbol.iterator]()
    for(let i of object){
        console.log(i)
    }
    console.log(iter.next())
    console.log(iter.next())
    console.log(iter.next())
    console.log(iter.next())


</script>
</html>